var prevRequestFiled = false;

function closeBtnHTML(cls) {
  var closebtnhtml = '';
  closebtnhtml += '<a href="#" class="' + cls + '" role="button" unselectable="on">';
  closebtnhtml += '  <span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;">close</span>';
  closebtnhtml += '</a>';
  return closebtnhtml;
}

function addMoreLanguagesUI(evt, val) {
  if (val == null) {
    val = '';
  }
  var $divlang = jQuery('#divLanguage').clone();
  $divlang.attr('id', '');
  $divlang.find('input').val(val);
  $divlang.append(closeBtnHTML("removeMoreLanguage"));
  jQuery('#divMoreLanguages').before($divlang);
  jQuery($divlang).find('a').click(removeMoreLanguage);
}

function removeMoreLanguage(evt) {
  jQuery(evt.currentTarget).parent().remove();
  return false;
}

/*
function addMoreWaterbodiesUI(evt, type, name) {
  if (name == null) {
    name = '';
  }
  var $divwaterbody = jQuery('#divWaterbody').clone();
  $divwaterbody.attr('id', '');
  if (type == null) {
    $divwaterbody.find('select')[0].selectedIndex = 0;
  }
  else {
    selectOptionByText($divwaterbody.find('select')[0], type);
  }
  $divwaterbody.find('input').val(name);
  $divwaterbody.append(closeBtnHTML("removeMoreWaterbody"));
  jQuery('#divMoreWaterbodies').before($divwaterbody);
  jQuery($divwaterbody).find('a').click(removeMoreWaterbody);
}
*/

function addWaterbody() {
  var mapped = jQuery('#divWaterbodies').children();
  mapped.css('border-color', 'rgb(217, 234, 245)');

  var w_type = jQuery('#divWaterbody').find('select').selectedTexts()[0];
  var w_name = trim(jQuery('#divWaterbody').find('input').val());
  if (w_name == '' || w_name.toLowerCase() == 'all') {
    w_name = 'All';
  }
  if (w_name.indexOf(':') != -1) {
    displayMessage('error', 'Special chars like : are not allowed.');
    return false;
  }
  var info = w_type;
  if (w_type == 'None' || w_type == 'All') {
    mapped.remove();
    disableElem(jQuery('#btnAddWaterbody'), true);
  }
  else {
    info += ':' + w_name;
  }

  var obj = getAlreadyMappedWaterbody('divWaterbodies', info);
  var match_num = obj.match_num;

  jQuery(obj.remove_divs).remove();
  if (match_num == -1) {
    addToMapping('divWaterbodies', info, "removeWaterbody", removeWaterbody);
    mapped = jQuery('#divWaterbodies').children();
    var len = mapped.length ;
    if (len == 3) {
      var cnt = 0;
      for (var i = 0; i < len; i++) {
        var txt = jQuery(mapped[i]).text();
        txt = txt.replace('\n', '');
        txt = txt.substring(0, txt.length - 5);
        txt = trim(txt);
        if (txt.split(':')[1] == 'All') {
          cnt++;
        }
      }
      
      if (cnt == 3) {
        mapped.remove();
        disableElem(jQuery('#btnAddWaterbody'), true);
        addToMapping('divWaterbodies', 'All', "removeWaterbody", removeWaterbody);
        jQuery('#divWaterbody').find('select[name=waterbody_type]').selectOptions('All');
      }
    }
  }
  else {
    jQuery(mapped[match_num]).css('border-color', 'red');
  }
}

/*
function removeMoreWaterbody(evt) {
  jQuery(evt.currentTarget).parent().remove();
  return false;
}
*/

function removeWaterbody(evt) {
  jQuery(evt.currentTarget).parent().remove();
  disableElem(jQuery('#btnAddWaterbody'), false);
  return false;
}

function getRegionsForCountry(evt) {
  disableElem(jQuery('#btnAddLocation'), true);
  var $siblings = jQuery(evt.currentTarget).parent().siblings();
  $siblings.hide(100);
  /*
  var countryid = parseInt(jQuery(evt.currentTarget).val());
  if (countryid > 0) {
  */
  var opt = jQuery(evt.currentTarget).selectedOptions()[0];
  var countryid = parseInt(opt.value);
  if (opt.Text != 'World') {
    jQuery(evt.currentTarget).parent().addClass("loading");
    var $select_region = $siblings.find('select[name=region]');
    var $select_city = $siblings.find('select[name=city]');
    $select_region.removeOption(/./); // Clear up the regions drop down since it will be a new country
    $select_city.removeOption(/./); // Clear up the cities dropdown
    jQuery.getJSON(Drupal.settings.basePath + 'observation/data/{"action":"getRegionsForCountry","params":{"countryid":' + countryid + '}}', function(json){
      //json.regions['0'] = 'All';
      $select_region.addOption(json.regions, false);
      //$select_region.sortOptions().selectOptions('0');
      //$select_region.addOption('0', 'All');
      jQuery(evt.currentTarget).parent().removeClass("loading");
      if ($select_region[0].length > 0) {
        selectOptionByText($select_region[0], opt.text);
        $select_region.parent().show(100);
        disableElem(jQuery('#btnAddLocation'), false);
      }
    });
  }
  else {
    disableElem(jQuery('#btnAddLocation'), false);
  }
}

function getCitiesForRegion(evt) {
  disableElem(jQuery('#btnAddLocation'), true);
  var $select_city = jQuery(evt.currentTarget).parent().siblings().find('select[name=city]');
  $select_city.parent().hide(100);
  var opt = jQuery(evt.currentTarget).selectedOptions()[0];
  var regionid = parseInt(jQuery(evt.currentTarget).val());
  var $select_region = jQuery(evt.currentTarget).parent().siblings().find('select[name=region]');
  if (opt.text != $select_region.val()) {
  //if (regionid > 0) {
    jQuery(evt.currentTarget).parent().addClass("loading");
    $select_city.removeOption(/./); // Clear up the cities dropdown
    jQuery.getJSON(Drupal.settings.basePath + 'observation/data/{"action":"getCitiesForRegion","params":{"regionid":' + regionid + '}}', function(json){
      json.cities['0'] = 'All';
      $select_city.addOption(json.cities, false);
      //$select_city.sortOptions().selectOptions('0');
      jQuery(evt.currentTarget).parent().removeClass("loading");
      if ($select_city[0].length > 1) {
        selectOptionByText($select_city[0], 'All');
        $select_city.parent().show(100);
      }
      disableElem(jQuery('#btnAddLocation'), false);
    });
  }
  else {
    disableElem(jQuery('#btnAddLocation'), false);
  }
}

function addLocation() {
  var mapped = jQuery('#divLocations').children();
  mapped.css('border-color', 'rgb(217, 234, 245)');

  var selects = jQuery('#divLocation').find('select');
  var country = jQuery(selects[0]).selectedTexts()[0];
  var info = country;
  if (country != 'World') {
    var region = jQuery(selects[1]).selectedTexts()[0];
    if (region != country) {
      info += ' > ' + region;
      var city = jQuery(selects[2]).selectedTexts()[0];
      if (city != 'All') {
        info += ' > ' + city;
      }
    }
  }
  else {
    mapped.remove();
    disableElem(jQuery('#btnAddLocation'), true);
  }

  var obj = getAlreadyMapped('divLocations', info);
  var match_num = obj.match_num;

  jQuery(obj.remove_divs).remove();
  if (match_num == -1) {
    addToMapping('divLocations', info, "removeLocation", removeLocation);
  }
  else {
    jQuery(mapped[match_num]).css('border-color', 'red');
  }
}

function removeLocation(evt) {
  jQuery(evt.currentTarget).parent().remove();
  disableElem(jQuery('#btnAddLocation'), false);
  return false;
}

function getMappingHTML(info, closesbtn_cls) {
  var loc = '<div style="border: 1px solid rgb(217, 234, 245); padding: 2px; margin: 2px;">';
  loc += info;
  loc += closeBtnHTML(closesbtn_cls);
  loc += '</div>';
  return loc;
}

function addToMapping(divid, info, closesbtn_cls, removeFunc) {
  jQuery('#' + divid).append(getMappingHTML(info, closesbtn_cls));
  jQuery('#' + divid).find('a').click(removeFunc);
}

function getAlreadyMapped(container_elem_id, info) {
  var mapped = jQuery('#' + container_elem_id).children();
  var len = mapped.length;
  var remove_divs = [];
  var match_num = -1;
  for (var i = 0; i < len; i++) {
    var txt = jQuery(mapped[i]).text();
    txt = txt.replace('\n', '');
    txt = txt.substring(0, txt.length - 5);
    txt = trim(txt);
    if (txt == info) {
      match_num = i;
      break;
    }
    else if (info.substring(0, txt.length) == txt) {
      match_num = i;
      break;
    }

    if (txt.length > info.length) {
      if (txt.substring(0, info.length) == info) {
        remove_divs.push(mapped[i]);
      }
    }
  }

  var obj = new Object();
  obj.match_num = match_num;
  obj.remove_divs = remove_divs;
  return obj;
}

function getAlreadyMappedWaterbody(container_elem_id, info) {
  var obj = getAlreadyMapped(container_elem_id, info);
  if (obj.match_num == -1) {
    var w_info = info.split(':');
    var w_type = w_info[0];
    var w_name = w_info[1];
    if (w_type != 'None' && w_type != 'All') {
      var mapped = jQuery('#' + container_elem_id).children();
      var len = mapped.length;
      for (var i = 0; i < len; i++) {
        var txt = jQuery(mapped[i]).text();
        txt = txt.replace('\n', '');
        txt = txt.substring(0, txt.length - 5);
        txt = trim(txt);
        var w_i = txt.split(':');
        if (w_i.length == 2) {
          var w_t = w_i[0];
          var w_n = w_i[1];
          if (w_t == w_type) {
            if (w_n == 'All') {
              obj.match_num = i;
              break;
            }
            else if (w_name == 'All') {
              obj.remove_divs.push(mapped[i]);
            }
          }
        }
      }
    }
  }
  
  return obj;
}

function getKingdoms() {
  disableElem(jQuery('#btnAddTaxanomy'), true);
  var $selKingdom = jQuery('#selKingdom');
  $selKingdom.removeOption(/./); // Clear up the cities dropdown
  jQuery.getJSON(Drupal.settings.basePath + 'observation/col/getKingdoms', function(json){
    $selKingdom.addOption('0', 'All', false);
    $selKingdom.addOption(json, false);
    disableElem(jQuery('#btnAddTaxanomy'), false);
  });
}

function getKingdomPhylums() {
  disableElem(jQuery('#btnAddTaxanomy'), true);
  jQuery('#selKingdom').parent().nextAll().hide(100);
  var $selPhylum = jQuery('#selPhylum');
  //$selPhylum.parent().hide(100);
  $selPhylum.removeOption(/./); // Clear up the cities dropdown
  var kingdom_id = parseInt(jQuery('#selKingdom').val());
  if (kingdom_id > 0) {
    jQuery('#selKingdom').parent().addClass('loading');
    jQuery.getJSON(Drupal.settings.basePath + 'observation/col/getKingdomPhylums/' + kingdom_id, function(json){
      $selPhylum.addOption('0', 'All', false);
      $selPhylum.addOption(json, false);
      if ($selPhylum[0].options.length > 1) {
        $selPhylum.parent().show(100);
      }
      jQuery('#selKingdom').parent().removeClass('loading');
      disableElem(jQuery('#btnAddTaxanomy'), false);
    });
  }
  else {
    disableElem(jQuery('#btnAddTaxanomy'), false);
  }
}

function getPhylumClasses() {
  disableElem(jQuery('#btnAddTaxanomy'), true);
  jQuery('#selPhylum').parent().nextAll().hide(100);
  var $selClass = jQuery('#selClass');
  //$selClass.parent().hide(100);
  $selClass.removeOption(/./); // Clear up the cities dropdown
  var phylum_id = parseInt(jQuery('#selPhylum').val());
  if (phylum_id > 0) {
    jQuery('#selPhylum').parent().addClass('loading');
    jQuery.getJSON(Drupal.settings.basePath + 'observation/col/getPhylumClasses/' + phylum_id, function(json){
      $selClass.addOption('0', 'All', false);
      $selClass.addOption(json, false);
      if ($selClass[0].options.length > 1) {
        $selClass.parent().show(100);
      }
      jQuery('#selPhylum').parent().removeClass('loading');
      disableElem(jQuery('#btnAddTaxanomy'), false);
    });
  }
  else {
    disableElem(jQuery('#btnAddTaxanomy'), false);
  }
}

function getClassOrders() {
  disableElem(jQuery('#btnAddTaxanomy'), true);
  jQuery('#selClass').parent().nextAll().hide(100);
  var $selOrder = jQuery('#selOrder');
  //$selOrder.parent().hide(100);
  $selOrder.removeOption(/./); // Clear up the cities dropdown
  var class_id = parseInt(jQuery('#selClass').val());
  if (class_id > 0) {
    jQuery('#selClass').parent().addClass('loading');
    jQuery.getJSON(Drupal.settings.basePath + 'observation/col/getClassOrders/' + class_id, function(json){
      $selOrder.addOption('0', 'All', false);
      $selOrder.addOption(json, false);
      if ($selOrder[0].options.length > 1) {
        $selOrder.parent().show(100);
      }
      jQuery('#selClass').parent().removeClass('loading');
      disableElem(jQuery('#btnAddTaxanomy'), false);
    });
  }
  else {
    disableElem(jQuery('#btnAddTaxanomy'), false);
  }
}

function getOrderFamilies() {
  disableElem(jQuery('#btnAddTaxanomy'), true);
  jQuery('#selOrder').parent().nextAll().hide(100);
  var $selFamily = jQuery('#selFamily');
  //$selFamily.parent().hide(100);
  $selFamily.removeOption(/./); // Clear up the cities dropdown
  var order_id = parseInt(jQuery('#selOrder').val());
  if (order_id > 0) {
    jQuery('#selOrder').parent().addClass('loading');
    jQuery.getJSON(Drupal.settings.basePath + 'observation/col/getOrderFamilies/' + order_id, function(json){
      $selFamily.addOption('0', 'All', false);
      $selFamily.addOption(json, false);
      if ($selFamily[0].options.length > 1) {
        $selFamily.parent().show(100);
      }
      jQuery('#selOrder').parent().removeClass('loading');
      disableElem(jQuery('#btnAddTaxanomy'), false);
    });
  }
  else {
    disableElem(jQuery('#btnAddTaxanomy'), false);
  }
}

function getFamiliyGenuses() {
  disableElem(jQuery('#btnAddTaxanomy'), true);
  jQuery('#selFamily').parent().nextAll().hide(100);
  var $selGenus = jQuery('#selGenus');
  //$selGenus.parent().hide(100);
  $selGenus.removeOption(/./); // Clear up the cities dropdown
  var family_id = parseInt(jQuery('#selFamily').val());
  if (family_id > 0) {
    jQuery('#selFamily').parent().addClass('loading');
    jQuery.getJSON(Drupal.settings.basePath + 'observation/col/getFamiliyGenuses/' + family_id, function(json){
      $selGenus.addOption('0', 'All', false);
      $selGenus.addOption(json, false);
      if ($selGenus[0].options.length > 1) {
        $selGenus.parent().show(100);
      }
      jQuery('#selFamily').parent().removeClass('loading');
      disableElem(jQuery('#btnAddTaxanomy'), false);
    });
  }
  else {
    disableElem(jQuery('#btnAddTaxanomy'), false);
  }
}

function getGenusSpecies() {
  disableElem(jQuery('#btnAddTaxanomy'), true);
  jQuery('#selGenus').parent().nextAll().hide(100);
  var $selSpecies = jQuery('#selSpecies');
  //$selSpecies.parent().hide(100);
  $selSpecies.removeOption(/./); // Clear up the cities dropdown
  var genus_id = parseInt(jQuery('#selGenus').val());
  if (genus_id > 0) {
    jQuery('#selGenus').parent().addClass('loading');
    jQuery.getJSON(Drupal.settings.basePath + 'observation/col/getGenusSpecies/' + genus_id, function(json){
      $selSpecies.addOption('0', 'All', false);
      $selSpecies.addOption(json, false);
      if ($selSpecies[0].options.length > 1) {
        $selSpecies.parent().show(100);
      }
      jQuery('#selGenus').parent().removeClass('loading');
      disableElem(jQuery('#btnAddTaxanomy'), false);
    });
  }
  else {
    disableElem(jQuery('#btnAddTaxanomy'), false);
  }
}

function addTaxanomy() {
  var mapped = jQuery('#divTaxanomies').children();
  mapped.css('border-color', 'rgb(217, 234, 245)');

  var info = '';
  var opt = jQuery('#selKingdom').selectedOptions()[0];
  var info = opt.text;
  if (parseInt(opt.value) != 0) {
    opt = jQuery('#selPhylum').selectedOptions()[0];
    if (parseInt(opt.value) != 0) {
      info += ' > ' + opt.text;
      opt = jQuery('#selClass').selectedOptions()[0];
      if (parseInt(opt.value) != 0) {
        info += ' > ' + opt.text;
        opt = jQuery('#selOrder').selectedOptions()[0];
        if (parseInt(opt.value) != 0) {
          info += ' > ' + opt.text;
          opt = jQuery('#selFamily').selectedOptions()[0];
          if (parseInt(opt.value) != 0) {
            info += ' > ' + opt.text;
            opt = jQuery('#selGenus').selectedOptions()[0];
            if (parseInt(opt.value) != 0) {
              info += ' > ' + opt.text;
              opt = jQuery('#selSpecies').selectedOptions()[0];
              if (parseInt(opt.value) != 0) {
                info += ' > ' + opt.text;
              }
            }
          }
        }
      }
    }
  }
  else {
    mapped.remove();
    disableElem(jQuery('#btnAddTaxanomy'), true);
  }

  var obj = getAlreadyMapped('divTaxanomies', info);
  var match_num = obj.match_num;

  jQuery(obj.remove_divs).remove();
  if (match_num == -1) {
    addToMapping('divTaxanomies', info, "removeTaxanomy", removeTaxanomy);
  }
  else {
    jQuery(mapped[match_num]).css('border-color', 'red');
  }
}

function removeTaxanomy(evt) {
  jQuery(evt.currentTarget).parent().remove();
  disableElem(jQuery('#btnAddTaxanomy'), false);
  return false;
}

function getParentEcosystems() {
  disableElem(jQuery('#btnAddEcosystem'), true);
  jQuery('#parent_ecosystem').parent().nextAll().hide(100);
  var $parent_ecosystem = jQuery('#parent_ecosystem');
  $parent_ecosystem.removeOption(/./); // Clear up the cities dropdown

  jQuery.getJSON(Drupal.settings.basePath + 'observation/data/{"action":"getParentEcosystems"}', function(json){
    if (parseInt(json.error) == 1) {
      alert(json.msg);
    }
    else {
      $parent_ecosystem.addOption('0', 'All', false);
      $parent_ecosystem.addOption(json.ecosystems, false);
      disableElem(jQuery('#btnAddEcosystem'), false);
    }
  });
}

function getChildEcosystems() {
  var parent_ecosystem = jQuery('#parent_ecosystem');
  var parent_id = parent_ecosystem.selectedOptions()[0].value;
  var $child_ecosystem = jQuery('#child_ecosystem');
  $child_ecosystem.parent().hide(100);
  $child_ecosystem.removeOption(/./);

  if (parent_id != 0) {
    parent_ecosystem.parent().addClass('loading');
    jQuery.getJSON(Drupal.settings.basePath + 'observation/data/{"action":"getChildEcosystems","params":{"parent_id":' + parent_id + '}}', function(json){
      if (parseInt(json.error) == 1) {
        alert(json.msg);
      }
      else {
        $child_ecosystem.addOption('0', 'All', false);
        $child_ecosystem.addOption(json.ecosystems, false);
        if ($child_ecosystem[0].options.length > 1) {
          $child_ecosystem.parent().show(100);
        }
      }
      parent_ecosystem.parent().removeClass('loading');
    });
  }
}

function addEcosystem() {
  var mapped = jQuery('#divEcosystems').children();
  mapped.css('border-color', 'rgb(217, 234, 245)');

  var selects = jQuery('#divEcosystem').find('select');
  var parent_ecosystem = jQuery(selects[0]).selectedTexts()[0];
  var info = parent_ecosystem;
  if (parent_ecosystem != 'All') {
    var child_ecosystem = jQuery(selects[1]).selectedTexts()[0];
    if (child_ecosystem != 'All') {
      info += ' > ' + child_ecosystem;
    }
  }
  else {
    mapped.remove();
    disableElem(jQuery('#btnAddEcosystem'), true);
  }

  var obj = getAlreadyMapped('divEcosystems', info);
  var match_num = obj.match_num;

  jQuery(obj.remove_divs).remove();
  if (match_num == -1) {
    addToMapping('divEcosystems', info, "removeEcosystem", removeEcosystem);
  }
  else {
    jQuery(mapped[match_num]).css('border-color', 'red');
  }
}

function removeEcosystem(evt) {
  jQuery(evt.currentTarget).parent().remove();
  disableElem(jQuery('#btnAddEcosystem'), false);
  return false;
}

function submitRequest() {
  if (prevRequestFiled && requestApproved) {
    var cont = confirm('Are you sure you want to submit? This operation will cause you to lose your validator status.');
    if (!cont) {
      return;
    }
  }
  jQuery('.messages.status').remove();
  clearMessages();

  captcha_code = trim(jQuery('#edit-wo-captcha').val());
  if (captcha_code == '') {
    displayMessage('error', 'Please enter the characters that you see in the captcha image.');
    return false;
  }

  var lang_inputs = jQuery('input[name=language]');
  var len = lang_inputs.length;
  var langs_arr = [];
  for (var i = 0; i < len; i++) {
    var lang = trim(jQuery(lang_inputs[i]).val());
    if (lang != '') {
      langs_arr.push(lang);
    }
  }

  var taxa_divs = jQuery('#divTaxanomies').children();
  var taxa = [];
  if (taxa_divs.length == 0) {
    taxa.push('All');
  }
  else {
    len = taxa_divs.length;
    for (var i = 0; i < len; i++) {
      var txt = jQuery(taxa_divs[i]).text();
      txt = txt.replace('\n', '');
      txt = txt.substring(0, txt.length - 5);
      txt = trim(txt);
      taxa.push(txt);
    }
  }

  var ecosystem_divs = jQuery('#divEcosystems').children();
  var ecosystems = [];
  if (ecosystem_divs.length == 0) {
    ecosystems.push('All');
  }
  else {
    len = ecosystem_divs.length;
    for (var i = 0; i < len; i++) {
      var txt = jQuery(ecosystem_divs[i]).text();
      txt = txt.replace('\n', '');
      txt = txt.substring(0, txt.length - 5);
      txt = trim(txt);
      ecosystems.push(txt);
    }
  }

  // var waterbodies = [];
  // var wtype_sels = jQuery('select[name=waterbody_type]');
  // var wname_inps = jQuery('input[name=waterbody_name]');
  // len = wtype_sels.length;
  // for (var i = 0; i < len; i++) {
    // if (wtype_sels[i].value != 'none') {
      // var obj = new Object();
      // obj.type = wtype_sels[i].value;
      // obj.name = wname_inps[i].value;
      // waterbodies.push(obj);
    // }
  // }
  var waterbody_divs = jQuery('#divWaterbodies').children();
  var waterbodies = [];
  if (waterbody_divs.length == 0) {
    waterbodies.push('All');
  }
  else {
    len = waterbody_divs.length;
    for (var i = 0; i < len; i++) {
      var txt = jQuery(waterbody_divs[i]).text();
      txt = txt.replace('\n', '');
      txt = txt.substring(0, txt.length - 5);
      txt = trim(txt);
      waterbodies.push(txt);
    }
  }

  var loc_divs = jQuery('#divLocations').children();
  var loc = [];
  if (loc_divs.length == 0) {
    loc.push('World');
  }
  else {
    len = loc_divs.length;
    for (var i = 0; i < len; i++) {
      var txt = jQuery(loc_divs[i]).text();
      txt = txt.replace('\n', '');
      txt = txt.substring(0, txt.length - 5);
      txt = trim(txt);
      loc.push(txt);
    }
  }

  var data = new Object();
  data.languages = langs_arr;
  data.taxanomy = taxa;
  data.ecosystem = ecosystems;
  data.waterbodies = waterbodies;
  data.location = loc;
  data.captcha = captcha_code;

  var request = new Object();
  request.action = 'submitValidationRequest';
  request.params = data;

  var url = Drupal.settings.basePath + 'observation/data';
  jQuery.post(
    url,
    {request: JSON.stringify(request)},
    function(data) {
      if (parseInt(data.error) == 1) {
        displayMessage('error', data.msg);
        return;
      } else {
        displayMessage('status', data.msg);
        return;
      }
    },
    'json'
  );
}

function getUserValidationExpertise(uid) {
  var params = new Object();
  params.uid = uid;

  var request = new Object();
  request.action = 'getUserValidationExpertise';
  request.params = params;

  var url = Drupal.settings.basePath + 'observation/data';
  jQuery.get(
    url,
    {request: JSON.stringify(request)},
    function(response) {
      if (parseInt(response.error) == 1) {
        displayMessage('error', response.msg);
        return;
      } else {
        updateUIWithData(response.data);
      }
    },
    'json'
  );
}

function updateUIWithData(data) {
  if (data.language) {
    prevRequestFiled = true;
    var languages = data.language;
    var len = languages.length;
    if (len > 0) {
      jQuery('#divLanguage input[name=language]').val(languages[0]);
      for (var i = 1; i < len; i++) {
        addMoreLanguagesUI(null, languages[i]);
      }
    }
  }

  if (data.taxanomy) {
    prevRequestFiled = true;
    var taxanomy = data.taxanomy;
    len = taxanomy.length;
    for (var i = 0; i < len; i++) {
      addToMapping('divTaxanomies', taxanomy[i], "removeTaxanomy", removeTaxanomy);
    }
  }

  if (data.ecosystem) {
    prevRequestFiled = true;
    var ecosystem = data.ecosystem;
    len = ecosystem.length;
    for (var i = 0; i < len; i++) {
      addToMapping('divEcosystems', ecosystem[i], "removeEcosystem", removeEcosystem);
    }
  }

  if (data.waterbody) {
    prevRequestFiled = true;
    var waterbodies = data.waterbody;
    len = waterbodies.length;
    // if (len > 0) {
      // var waterbody = waterbodies[0].split(':');
      // selectOptionByText(jQuery('#divWaterbody select[name=waterbody_type]')[0], waterbody[0]);
      // jQuery('#divWaterbody input[name=waterbody_name]').val(waterbody[1]);
      // for (var i = 1; i < len; i++) {
        // waterbody = waterbodies[i].split(':');
        // addMoreWaterbodiesUI(null, waterbody[0], waterbody[1]);
      // }
    // }
    for (var i = 0; i < len; i++) {
      addToMapping('divWaterbodies', waterbodies[i], "removeWaterbody", removeWaterbody);
    }
    if (len == 1 && (waterbodies[0] == 'All' || waterbodies[0] == 'None')) {
      disableElem(jQuery('#btnAddWaterbody'), true);
    }
  }

  if (data.location) {
    prevRequestFiled = true;
    var location = data.location;
    len = location.length;
    for (var i = 0; i < len; i++) {
      addToMapping('divLocations', location[i], "removeLocation", removeLocation);
    }
  }
}

jQuery(document).ready(function() {
  getKingdoms();
  jQuery('#selKingdom').change(getKingdomPhylums);
  jQuery('#selPhylum').change(getPhylumClasses);
  jQuery('#selClass').change(getClassOrders);
  jQuery('#selOrder').change(getOrderFamilies);
  jQuery('#selFamily').change(getFamiliyGenuses);
  jQuery('#selGenus').change(getGenusSpecies);
  jQuery('#btnAddTaxanomy').click(addTaxanomy);

  getParentEcosystems();
  jQuery('#btnAddEcosystem').click(addEcosystem);
  jQuery('#parent_ecosystem').change(getChildEcosystems);

  jQuery('#btnMoreLanguages').click(addMoreLanguagesUI);

  //jQuery('#btnMoreWaterbodies').click(addMoreWaterbodiesUI);
  jQuery('#btnAddWaterbody').click(addWaterbody);

  selectOptionByText(jQuery('select[name=country]')[0], 'World');
  jQuery('select[name=country]').change(getRegionsForCountry);
  jQuery('select[name=region]').change(getCitiesForRegion);
  jQuery('#btnAddLocation').click(addLocation);

  jQuery('#btnSubmit').click(submitRequest);

  if (uid) {
    getUserValidationExpertise(uid);
  }
});